package commands;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

import main.InputHandler;
import util.*;

public class MessageCommand extends Command {
	public static String name = "message";
	public static String help = "Name: message \n>message {str:opt('server','client')} {IF(prev.opt='client'):str} {str} \n>message (type of port) (if 'client' client name) (message) " +
			"\n>Going to be used to message another computer, but does nothing for now.";
	
	public static boolean test(InputHandler handler, StringList words){
		if(StringChecker.testWord(words, 0, "message")){
			if(words.size() > 1){
				if(words.get(1).equals("server")){
					if(words.size() > 2){
						if(ConnectCommand.socket != null){
							try {
								ConnectCommand.socket.write(words.get(2)+" "+DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date()));
							} catch (IOException e) {
								handler.terminal.write("Couldn't write");
								return true;
							}
							handler.terminal.write("Message sucessful");
						}else{
							handler.terminal.write("Socket is null");
						}
					}
					return true;
				}else if(words.get(1).equals("client")){
					if(words.size() > 2 && OpenPortCommand.sockets.containsKey(words.get(2))){
						String person = words.get(2);
						if(words.size() > 3){
							try {
								OpenPortCommand.sockets.get(person).write(words.get(3));
							} catch (IOException e) {
								handler.terminal.write("Couldn't write");
								return true;
							}
						}else{
							handler.terminal.write("No message provided");
						}
					}else{
						handler.terminal.write("Not a valid recipient");
					}
					return true;
				}else{
					handler.terminal.write("Invalid target");
					return true;
				}
			}
			return true;
		}
		return false;
	}
}
